const { app, BrowserWindow, Menu, Tray, ipcMain, shell, dialog } = require('electron');
const path = require('path');
const fs = require('fs');
const ipcHandlers = require('./ipcHandlers');

ipcMain.handle('check-network-status', ipcHandlers.checkNetworkStatus);
ipcMain.handle('get-class-data', ipcHandlers.getClassData);
ipcMain.handle('save-class-data', ipcHandlers.saveClassData);
ipcMain.handle('delete-class-data', ipcHandlers.deleteClassData);
ipcMain.handle('save-student-data', ipcHandlers.saveStuData);
ipcMain.handle('get-student-data', ipcHandlers.getStuData);
ipcMain.handle('delete-student', ipcHandlers.deleteStuData);
ipcMain.handle('get-student-count', ipcHandlers.getClassStudentCount);
ipcMain.handle('get-class-data-by-no', ipcHandlers.getClassDataByNo);
ipcMain.handle('update-stu-data', ipcHandlers.updateStuData);
ipcMain.handle('get-stus-data-by-class-no', ipcHandlers.getStuDataByClassNo);
ipcMain.handle('add-points', ipcHandlers.addPoints);
ipcMain.handle('add-attempts', ipcHandlers.addAttempts);
ipcMain.handle('init-app', ipcHandlers.initFile);
ipcMain.handle('write-data', ipcHandlers.writeData);
ipcMain.handle('save-file', async (event) => {
  const sourceFilePath = path.join(__dirname, '学生信息.xlsx');
  const savePath = dialog.showSaveDialogSync(mainWindow, {
    title: '保存文件',
    defaultPath: path.basename(sourceFilePath),
    buttonLabel: '保存',
    filters: [{ name: '所有文件', extensions: ['*'] }],
  });

  if (savePath) {
    try {
      const fileContent = fs.readFileSync(sourceFilePath);
      fs.writeFileSync(savePath, fileContent);

      return { success: true, path: savePath };
    } catch (error) {
      alert(error.message)
      return { success: false, error: error.message };
    }
  }

  return { success: false, error: '用户取消了保存' };
});
const userDataPath = app.getPath('userData');
const userFilePath = path.join(userDataPath, 'user.json');
let userInfo = {
  username: '未登录用户',
  signature: '初始签名',
  token: '',
  userAvatar:''
};

function loadUserInfo() {
  try {
    if (fs.existsSync(userFilePath)) {
      const data = fs.readFileSync(userFilePath, 'utf-8');
      userInfo = JSON.parse(data);
    }
  } catch (error) {
    console.error('读取用户信息失败:', error);
  }
}

function saveUserInfo() {
  try {
    fs.writeFileSync(userFilePath, JSON.stringify(userInfo), 'utf-8');
  } catch (error) {
    console.error('保存用户信息失败:', error);
  }
}

loadUserInfo();

ipcMain.handle('get-user-info', async () => {
  return { ...userInfo };
});

ipcMain.on('update-user-info', (event, newUserInfo) => {
  userInfo = { ...userInfo, ...newUserInfo };
  saveUserInfo();
  BrowserWindow.getAllWindows().forEach(win => {
    win.webContents.send('user-info-updated', { ...userInfo });
  });
});




let mainWindow, settingsWindow;
let tray;
const isDev = true;

function createSettingsWindow() {
  settingsWindow = new BrowserWindow({
    width: 900,
    height: 700,
    frame: false,
    show: false,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      nodeIntegration: false,
      contextIsolation: true,
    },
  });

  let settingsURL;
  if (isDev) {
    settingsURL = 'http://localhost:8888/#/profile';
  } else {
    settingsURL = `file://${path.join(__dirname, '../dist/index.html')}#/profile`;
  }

  settingsWindow.loadURL(settingsURL);

  if (isDev) {
    settingsWindow.webContents.openDevTools();
  }

  settingsWindow.on('closed', () => {
    settingsWindow = null;
  });
}

function createWindow() {
  mainWindow = new BrowserWindow({
    width: 1200,
    height: 800,
    frame: false,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      nodeIntegration: false,
      contextIsolation: true,
      enableRemoteModule: false,
    },
  });

  if (isDev) {
    mainWindow.loadURL('http://localhost:8888');
    mainWindow.webContents.openDevTools();
  } else {
    mainWindow.loadFile(path.resolve(__dirname, '../dist/index.html'));
  }

  mainWindow.on('close', (event) => {
    event.preventDefault();
    mainWindow.hide();
    mainWindow.setSkipTaskbar(true);
  });

  ipcMain.on('resize-window', (event, size) => {
    const window = BrowserWindow.fromWebContents(event.sender);
    if (window) window.setSize(size.width, size.height);
  });

  ipcMain.on('minimize-window', (event) => {
    const window = BrowserWindow.fromWebContents(event.sender);
    if (window) window.minimize();
  });

  ipcMain.on('toggle-fullscreen', (event) => {
    const window = BrowserWindow.fromWebContents(event.sender);
    if (window) {
      const isFullScreen = window.isFullScreen();
      window.setFullScreen(!isFullScreen);
      if (isFullScreen) {
        window.webContents.send('window-unmaximized');
      } else {
        window.webContents.send('window-maximized');
      }
    }
  });

  ipcMain.on('close-window', (event) => {
    const window = BrowserWindow.fromWebContents(event.sender);
    if (window) {
      window.hide();
      window.setSkipTaskbar(true);
    }
  });

  ipcMain.on('hide-window', (event) => {
    const window = BrowserWindow.fromWebContents(event.sender);
    if (window) window.hide();
  });

  ipcMain.on('open-external', (event, url) => {
    shell.openExternal(url);
  });

  ipcMain.on('open-settings-window', () => {
    if (settingsWindow && !settingsWindow.isDestroyed()) {
      settingsWindow.show();
    }
  });

  ipcMain.on('open-settings-and-show-login', () => {
    if (settingsWindow instanceof Object && !settingsWindow.isDestroyed()) {
      settingsWindow.show();
    } else {
      createSettingsWindow();
    }
    settingsWindow.webContents.once('did-finish-load', () => {
      settingsWindow.webContents.send('show-login-modal');
    });

    if (!settingsWindow.webContents.isLoading()) {
      settingsWindow.webContents.send('show-login-modal');
    }
  });
}

function createTray() {
  tray = new Tray(path.join(__dirname, 'icon.png'));

  const contextMenu = Menu.buildFromTemplate([
    {
      label: '显示窗口',
      click: () => {
        mainWindow.show();
        mainWindow.setSkipTaskbar(false);
      },
    },
    {
      label: '退出应用',
      click: () => {
        mainWindow.destroy();
        if (settingsWindow) {
          settingsWindow.destroy();
        }
        app.quit();
      },
    },
    {
      label: '关于软件',
      click: () => {
        shell.openExternal('http://49.233.250.28/');
      },
    },
  ]);
  Menu.setApplicationMenu(null);
  tray.setContextMenu(contextMenu);
  tray.setToolTip('智联慧动课堂');

  tray.on('click', () => {
    mainWindow.show();
    mainWindow.setSkipTaskbar(false);
  });
}

app.whenReady().then(() => {
  createWindow();
  createSettingsWindow();
  createTray();

  app.on('activate', function () {
    if (BrowserWindow.getAllWindows().length === 0) createWindow();
  });
});
ipcMain.handle('http-request', async (event, url, options = {}) => {
  return new Promise((resolve, reject) => {
    try {
      const request = net.request({
        method: options.method || 'GET',
        url,
        redirect: 'follow',
      });
      
      const headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
        ...options.headers
      };
      
      Object.entries(headers).forEach(([key, value]) => {
        request.setHeader(key, value);
      });
      
      let responseData = '';
      
      request.on('response', (response) => {
        response.on('data', (chunk) => {
          responseData += chunk.toString('utf8');
        });
        
        response.on('end', () => {
          resolve({
            data: responseData,
            status: response.statusCode,
            headers: response.headers
          });
        });
        
        response.on('error', (error) => {
          reject(error);
        });
      });
      
      request.on('error', (error) => {
        reject(error);
      });
      request.end();
      
    } catch (error) {
      reject(error);
    }
  });
});
// 注释掉 window-all-closed 事件处理
// app.on('window-all-closed', () => {
//   if (process.platform !== 'darwin') {
//     app.quit();
//   }
// });
